import Vue from "vue"
import VueRouter from "vue-router"
import router from "./router"
import store from "./store"
import notification from "ant-design-vue/es/notification"
import { message } from "ant-design-vue"
import { autoLogin } from './api/login'
import { getPostParentName, changeCurrentPost, getProjectIdByOrgId, getCurrentUserBranchCom3 } from '@/api/commons.js'

import { ssoUriPrefix, clientId, tokenUriPrefix, authType } from "@/config"
import AcloudVueOAuthPlugin from "@/oauth/ycloud-vue-oauth-plugin"
import { forEach } from "lodash"

import { mapActions } from 'vuex'


Vue.use(VueRouter)

const whiteList = ["/login", "/register", "/registerResult", "/meetingRoomProjection", "/meetingRoomProjectionDetail", '/bimSharePreview', '/quality/measuredAmount/map/pointInfo'] // no redirect whitelist
const loginRoutePath = "/"
const defaultRoutePath = "/index"   // 默认路径直接进入 自定义配置
const openList = ['/share/asset']

if (authType === "oauth2") {
  Vue.use(AcloudVueOAuthPlugin, {
    sso_uri_prefix: ssoUriPrefix,
    client_id: clientId
  })
} else {
  console.error("不支持的验证类型：" + authType)
}
const accessError = e => {
  const data = (e.response && e.response.data) || {}
  notification.error({
    message: "提示",
    description: data.error_description
  })
  //无效令牌
  if (parseInt(data.status) === 401) {
    store.dispatch("SetHasRouters", false)
    // 退出登录
    Vue.getAcloudProvider().logout()
  }
}

router.beforeEach(async (to, from, next) => {

  // console.log(to.fullPath,to.redirectedFrom)
  // if (to.fullPath === '/noFound') {
  //   to.redirectedFrom !== '/404.html' && window.location.replace("/404.html")
  //   return
  // }
  if (openList.indexOf(to.path) !== -1) {
    console.log('二维码分享界面放行');
    next()
    return
  }
  if (to.query.loginType && to.query.loginType === 'auto') {
     // 从app跳转到审批详情时，需要设置token，避免重新登录
    const { access_token, refresh_token } = to.query
    if (access_token) {
      Vue.getAcloudProvider().setAccessToken(access_token)
      store.dispatch("GetUserInfo", { access_token, refresh_token })
    }
    if (to.query.loginType && to.query.loginType === 'auto') {
      localStorage.removeItem('access_token')
    }
    if (to.path === '/' || to.path === '/login') {
      window.location.href = 'http:' + '//' + process.env.VUE_APP_PORTAL
    }
    if (!localStorage.getItem('access_token')) {
      console.log(2);
      const params = {
        "clientId": '1b2f3298686d4dfdbb1dc845fe1d00d4',
        "clientSecret": 'yVbe3AcXSSECaV5SUhBIs7Vh5pC3krIQkDL',
        "password": '{crypto}04801CBEE4B30C2F982BB0B6D3D0DA84243A98043A58A8B67E8231080BEA1AEA6BF953D9424870AE672476352D35532F24F945DD979C9E29E3ACA3C5AC20ED6A4000311ABCFCD1ACB03E1942BE1E2C11BB87775C9AE8E600C90C29A351C98E0931A59D2612F3AE08A0E229EBB55686D2F4DF35CC03072E3E8BEDF3AC79FB03EAEC2029F1DD2B5064496F04063DA00EDE8C42C7BA896FBE412E241AC27CFB97AC6DC78B066FB5B21856D3BC8E74CBDDCB20E113CFB94221',
        "grantType": "password_double",
        "userId": to.query.userId,//'5e3a42971f9a4eb1ad74791d9dd7c4ed', //to.query.userId
        "code": to.query.code,
        "type": to.query.type
      }
      const data = await autoLogin(params)
      // store.dispatch('Autologin', params)

      if (data.code === 200) {
        const { access_token, refresh_token } = data.data
        if (to.query.type === 'bigdata') {
          window.location.href = process.env.VUE_APP_PM_BASEURL + `/auth-userapi/yyzhzx/api/authority/v1/token?accessToken=${access_token}&callback=${process.env.VUE_APP_PM_DATA}`
        } else if (to.query.type === 'hr') {
          window.location.href = 'https://hr.cscecxn.com/api/auth/login_by_sso?sso=customer_sso&next=/%23/index&token=' + access_token
        } else if (to.query.type === 'xnzx') {
          window.location.href = "http://zzxnzx.st.pazc.paic.com.cn/sso/cscecxn/authorize?token=" + access_token
        } else {
          localStorage.setItem('access_token', JSON.stringify(access_token))
          Vue.getAcloudProvider().setAccessToken(access_token)
          const userInfoRes = await store.dispatch("GetUserInfo", data.data)
          console.log(userInfoRes, 'userInfoRes')

          const res66 = await getPostParentName({ id: data.data.userId })
          sessionStorage.setItem('postsList', JSON.stringify(res66.data || []))
          store.dispatch('getOrgLabel')
          const res = await changeCurrentPost({ postId: res66.data[0].id })
          const updateUserInfo = {
            ...userInfoRes,
            currentPost: {
              ...res.data, // 这里面的id为组织机构ID
              postId: res66.data[0].id // 所选择岗位的id
            }
          }
          if (updateUserInfo.currentPost.code === 'PD') {
            let res2 = await getProjectIdByOrgId({ id: updateUserInfo.currentPost.id })
            if (res2.code === 200) {
              updateUserInfo.currentPost = {
                ...updateUserInfo.currentPost,
                projectId: res2.data.projectId,
                projectName: res2.data.projectName
              }
            }
            let res1 = await getCurrentUserBranchCom3({ tagCodes: ['BC'] })
            if (res1.code === 200) {
              updateUserInfo.currentPost = { ...updateUserInfo.currentPost, ...res1.data[0] }
            }
          } else {
            let company = {
              orgId: updateUserInfo.currentPost.id,
              orgName: updateUserInfo.currentPost.name,
              tagCode: updateUserInfo.currentPost.code
            }
            updateUserInfo.currentPost = { ...updateUserInfo.currentPost, ...company }
          }
          console.log(updateUserInfo, 'updateUserInfo')
          Vue.getAcloudProvider().setUserInfo(updateUserInfo)
          // sessionStorage.setItem('ycloud-user_info', JSON.stringify(updateUserInfo))
          next({ path: to.path, query: { ...to.query, loginType: '' } })
          return
        }
        return

      }
    }
  }

  // 已经登录
  // Vue.getAcloudProvider().logout()
  else if (Vue.getAcloudProvider().hasAccessToken()) {
    // debugger
    const pathMap = store.getters["tabInfo/GET_PATH_MAP"]
    // console.log(pathMap)
    // console.log('permission',to)
    // console.log('permission-pathMap',pathMap)

    let resIndex = pathMap.findIndex(v => v.path === to.path)
    if (resIndex !== -1) {
    } else {
      //没有新的tab页面，并且没有配置ignoreNoTab
      if (to.meta.noTab && !to.query.ignoreNoTab) {
      } else {
        //检测开的标签页是否超过10个
        // let cachePages = store.state.tabInfo.cachePages
        if (pathMap && pathMap.length >= 10) {
          return message.warn('标签页不能超过10个')
        }
      }
    }

    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
    } else {
      // check login user.roles is null
      if (!store.getters.hasSetRouters) {
        // 获取按钮权限资源
        store.dispatch("GetBtnResources")
        // request login userInfo
        store.dispatch("GetMenus").then(res => {
          // generate dynamic router
          store.dispatch("GenerateRoutes", { res }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            router.addRoutes(store.getters.addRouters)
            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
        }).catch((e) => {
          accessError(e)
        })
        //   // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
        //   store.dispatch('Logout').then(() => {
        //     next({ path: loginRoutePath, query: { redirect: to.fullPath } })
        //   })
        // })
      } else {
        next()
      }
    }
    // }


  } else {
    let response = Vue.getAcloudProvider().parseResponse()
    if (response != null) {
      response.then(response1 => {
        // 去掉浏览器地址栏中查询参数?ticket
        let href = window.location.href
        if (href.indexOf("?") !== -1) {
          href = href.split("?")[0]
          window.location.href = href
        } else {
          next({ path: defaultRoutePath })
        }
      }).catch(e => {
        accessError(e)
      })
      return
    }
    // store.dispatch('SetHasRouters',true)
    // 没有登录
    // Vue.getAcloudProvider().login()
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next("/login")
    }

  }
})
// router.aftereEach((to, from) => {

// })

export default router
